<?php

session_start();

App::uses('Controller', 'Controller');

App::import('Vendor','Google_Client',array('file'=>'google-api-php-client'. DS .'src'. DS .'Google_Client.php'));
App::import('Vendor','Google_TasksService',array('file'=>'google-api-php-client'. DS .'src'. DS .'contrib' . DS . 'Google_TasksService.php'));

class TaskController extends Controller
{
	public function __construct($request = null, $response = null)
	{
		parent::__construct($request, $response);
		$this->gclient = new Google_Client;
		$client = &$this->gclient;
		$client->setClientId(Configure::read('Google.clientId'));
		$client->setClientSecret(Configure::read('Google.secretKey'));
		$client->setDeveloperKey(Configure::read('Google.developerKey'));
		$client->setRedirectUri('http://127.0.0.1/meal-plan/task/oauth2callback');
		$client->setApplicationName("Focus");
		
		$this->gtasks = new Google_TasksService($client);
		
		if (isset($_SESSION['access_token'])) {
			$client->setAccessToken($_SESSION['access_token']);
		} elseif (isset($_GET['code'])) {
			$client->authenticate();
			$_SESSION['access_token'] = $client->getAccessToken();
		} else {
			$authUrl = $client->createAuthUrl();
			print "<a href='$authUrl'>Connect Me!</a>";
		}
	}
	
	public function index()
	{
		$lists = $this->gtasks->tasklists->listTasklists();
		foreach ($lists['items'] as $list) {
			print "<h3>{$list['title']}</h3>";
			var_dump($list);
			#$tasks = $tasksService->tasks->listTasks($list['id']);
		}
	}
	
	public function add()
	{
		$task = new Google_Task;
		$task->setTitle('Dave test');
		
		try {
			$result = $this->gtasks->tasks->insert('MDMzODM5OTE0NTYxNzE2OTMwOTE6OTMyNjY4NzE1OjA', $task);
		} catch (Exception $ex) {
			throw new InternalErrorException($ex->getMessage());
		}
		var_dump($result);
	}
	
	public function oauth2callback()
	{
		$client = &$this->gclient;
		$this->redirect();
	}
	
	public function __destruct() 
	{
		$_SESSION['access_token'] = $this->gclient->getAccessToken();
	}
}
